<?php

namespace App\Listeners\Kms;

use App\Events\Kms\TaskNodeFinishEvent;
use App\Models\Kms\Task\TaskModel;
use App\Service\Kms\Task\Common\BaseTask;

class TaskNodeFinishListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param TaskNodeFinishEvent $nodeFinishEvent
     * @return void
     * @throws \Exception
     */
    public function handle(TaskNodeFinishEvent $nodeFinishEvent)
    {
        $logData = ["taskId" => $nodeFinishEvent->taskId, "nodeId" => $nodeFinishEvent->nodeId];
        logInfo("【 任务节点完成 】【 异步日志写入 】", collect($logData), true, false);

        try {
            $taskModel = TaskModel::query()->where("id", $nodeFinishEvent->taskId)->with([
                "templateRel",
                "taskNodesRel" => function ($query) use ($nodeFinishEvent) {
                    $query->where("id", $nodeFinishEvent->nodeId);
                }
            ])->first();

            BaseTask::getTaskInstance($taskModel->templateRel->templateType)->handleTaskNodeFinishEvent($taskModel);
        } catch (\Exception $exception) {
            logException("【 任务节点完成 】【 异步事件处理失败 】 ", $exception, $logData, true, true);
        }
    }

}
